﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Options
{
    internal class IntegratedCodeAnalysisCommandBehaviorsConverter : EnumConverter
    {
        public IntegratedCodeAnalysisCommandBehaviorsConverter(Type type)
            : base(type)
        {
        }


        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(string);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            var field = EnumType.GetField(Enum.GetName(EnumType, value));
            var attr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
            return attr != null ? attr.Description : value.ToString();
        }

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            foreach (var field in EnumType.GetFields())
            {
                var attr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
                if ((attr != null) && ((string)value == attr.Description))
                {
                    return Enum.Parse(EnumType, field.Name);
                }
            }
            return Enum.Parse(EnumType, (string)value);
        }
    }
}
